<?php
class TController implements TController_Interface, TPlugin_Interface, TPlugin_Front_Interface
{
	public $priority = TControllerConf::PRIORITY;
	protected $self;
	protected $req = array();

	public function pry(){
		if(isset($this->priority)){
			return $this->priority;
		}else{
			return self::PRIORITY;
		}
	}

	public function set(){
		$this->self = TInstances::getSelf();
	}

	public function req($i){
		$this->req = $i;
	}

	public function act(){
		if(TControllerConf::RUTING !== true) return;

		TControllerConf::init();
		$this->exchange();

		$rute = $this->getController($this->req);
		if(isset($rute[0]) && strlen($rute[0]) > 0){
			$class = $rute[0];
		}else{
			$class = TControllerConf_DEFAULT_CLASS;
		}
		$class = ucfirst($class);
		$class = $class.TControllerConf_CONTROLLER;

		if(isset($rute[1]) && strlen($rute[0]) > 0){
			$method = $rute[1];
		}else{
			$method = TControllerConf_DEFAULT_METHOD;
		}

		if(!is_readable(TControllerConf_DIR.DS.$class.'.php')){
			$class = ucfirst(TControllerConf_404CLASS).TControllerConf_CONTROLLER;
			if(is_readable(TControllerConf_DIR.DS.$class.'.php')){
				require_once(TControllerConf_DIR.DS.$class.'.php');
				$method = TControllerConf_404METHOD;
			}else{
				return;
			}
		}

		require_once(TControllerConf_DIR.DS.$class.'.php');
		if(!class_exists($class)) return;

		$controller = new $class;

		if(!($controller instanceof TController_Action_Interface)) return;

		if(!method_exists($controller, $method)){
			$class = ucfirst(TControllerConf_404CLASS).TControllerConf_CONTROLLER;
			if(!is_readable(TControllerConf_DIR.DS.$class.'.php')) return;
			require_once(TControllerConf_DIR.DS.$class.'.php');
			if(!class_exists($class)) return;
			$controller = new $class;
			if(!method_exists($controller, TControllerConf_404METHOD)) return;
			$method = TControllerConf_404METHOD;
		}

		$controller->setRequest($this->req);
		$controller->setSelf();

		try{
			$controller->$method($rute);
		}catch(Exception $e){
			$controller->errorAction($e);
		}
	}
	public function getController($req){
		$rute = @$req[TControllerConf::RUTE_REQUEST];
		return explode('/', $rute);
	}

	private function exchange(){
		if(interface_exists('TController_TemplateAction_Interface')){
			$dir = dirname(__FILE__);
			require_once($dir.DS.'Default_TController_TemplateAction.php');
		}
	}

	public function etc(){}
}
